var express = require("express");
var router = express.Router();
var {
  typeOneModel,
  typeTwoModel,
  BooksModel,
  historyModel,
  carlistModel,
  friendModel,
  messageModel,
  usersModel,
  reviewModel
  , commentModel
} = require("../model/model");

var multiparty = require("multiparty");
/* GET home page. */
// router.post("/upload", (req, res) => {
//   let form = new multiparty.Form();
//   form.uploadDir = "upload";
//   form.parse(req, (err, file, imgData) => {
//     res.send({
//       code: 200,
//       path: "http://127.0.0.1:3000/" + imgData.file[0].path,
//     });
//   });
// });

// router.post("/goodsadd", (req, res) => {
//   goodsModel.create(req.body);
//   res.send({
//     code: 200,
//     msg: "添加成功",
//   });
// });

// router.get("/goodslist", async (req, res) => {
//   let goodslist = await goodsModel.find();
//   res.send({
//     code: 200,
//     msg: "查询成功",
//     goodslist,
//   });
// });
router.get('/carlist', async (req, res) => {
  let carlist = await carlistModel.find()
  res.send({ carlist })
})

router.post('/caradd', (req, res) => {
  carlistModel.create(req.body)
  res.send({
    code: 200,
    msg: '添加成功'
  })
})

router.put('/carupdate', async (req, res) => {
  let { id, checked } = req.body
  await carlistModel.updateOne({ _id: id }, { checked: checked })
  res.send({
    code: 200,
    msg: '修改成功'
  })
})

// router.put('/carupdatemany', async (req, res) => {
//   let { ids } = req.body
//   console.log('update=>',ids);
// //   console.log(id, checked)
//   // await carlistModel.updateMany({ _id: {$in:ids} }, { is_pay: true ,checked:false})
//   // res.send({
//   //   code: 200,
//   //   msg: '修改成功'
//   // })
// })
//批量删除
router.post('/cardeletemany', async (req, res) => {
  let { ids } = req.body
  await carlistModel.deleteMany({ _id:ids})
  res.send({
    code: 200,
    msg: '删除成功'
  })
})
//商品评论
router.get('/review', async (req, res) => {
  let review = await reviewModel.find()
  res.send({ review })
})
router.post('/reviewadd', (req, res) => {
  reviewModel.create(req.body)
  res.send({
    code: 200,
    msg: '添加成功'
  })
})

//作者回复
router.get('/comment', async (req, res) => {
  let comment = await commentModel.find()
  res.send({ comment })
})
router.post('/commentadd', (req, res) => {
  commentModel.create(req.body)
  res.send({
    code: 200,
    msg: '添加成功'
  })
})

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

// 图书添加
router.post('/add', (req, res) => {
  BooksModel.create(req.body)
  res.send({
    code: 200,
    msg: "添加成功"
  })
})

// 图书列表
router.get("/list", async (req, res) => {
  let data = await BooksModel.find();
  res.send({
    code: 200,
    msg: "查询成功",
    data
  })
})


// 图片上传
router.post("/upload", (req, res) => {
  let form = new multiparty.Form()
  form.uploadDir = 'upload'
  form.parse(req, (err, filder, imgDate) => {
    res.send({
      code: 200,
      msg: "上传成功",
      img: "http://localhost:3000/" + imgDate.file[0].path
    })
  })
})

///
// 搜索用户好友数据接口
router.post('/friends', async (req, res) => {
  const { friendId } = req.body
  const obj = {}
  if (friendId) obj._id = { $in: friendId }
  const friendList = await usersModel.find(obj)
  res.send({
    code: 200,
    friendList
  })
})

// 用户添加好友接口
router.post('/add-user', async (req, res) => {
  const { uid, friendId } = req.body
  const fids = [...new Set(friendId)]
  await usersModel.findOneAndUpdate({ uid }, { $push: { friendId: fids } })
  res.send({
    code: 200,
    msg: "操作成功"
  })
})



// 搜索用户数据接口
router.post('/user', async (req, res) => {
  const { username, password } = req.body
  const obj = {}
  if (username) obj.username = username
  const user = await usersModel.find(obj)
  res.send({
    code: 200,
    user,
  })
})

// 聊天信息数据接口
router.post('/message', async (req, res) => {
  const { uid, sid, formId } = req.query
  let obj = {}
  if (uid && sid) obj.$and = [{ uid: uid }, { sid: sid }]
  if (formId) obj.formId = formId
  const messageList = await messageModel.find(obj)

  res.send({
    code: 200,
    messageList
  })
})

//类别接口
router.get("/type", async (req, res) => {
  let data1 = await typeOneModel.find().lean()
  let data2 = await typeTwoModel.find()
  console.log('====================================');
  console.log(data1);
  console.log('====================================');
  console.log(data2)
  data1.forEach(ele => {
    data2.forEach(ele2 => {
      if (String(ele._id) == String(ele2.typeOneId)) {
        if (!ele.children) {
          ele.children = []
        }
        ele.children.push(ele2)
      }
    })
  })
  console.log('====================================');
  console.log(data1);
  console.log('====================================');
  res.send({
    code: 200,
    data: data1
  })
})


//支付宝


//引入支付宝配置文件
const alipaySdk=require('./alipay');
const AlipayFormData = require('alipay-sdk/lib/form').default;
router.post('/api/payment',function(req,res){
  console.log(req.body,'aaaaaaaaaaaaa')
  //订单号
  let orderId = req.body.orderId;
  //商品总价
  let price = req.body.price;
  //购买商品的名称
  let name = req.body.name;
  // 开始对接支付宝API
  const formData = new AlipayFormData();
  //调用setMethod 并传入get,会返回可以跳转到支付页面的url,
  formData.setMethod("get");
  // 支付时信息
  const bizContent = {
      out_trade_no: orderId, //订单号
      product_code: "FAST_INSTANT_TRADE_PAY",
      total_amount: price, //总价格
      subject: name, //商品名称
      body: "商品详情", //商品描述
  };
  formData.addField("bizContent", bizContent);

  //支付成功或失败的返回链接（前端页面）
  formData.addField("returnUrl", "http://127.0.0.1:5173/payover");

  // 返回promise
  const result = alipaySdk.exec(
      // "alipay.trade.page.pay",
      "alipay.trade.wap.pay", 
      {},
      { formData: formData }
  ).catch(error => console.error('caught error!', error));

  //对接支付宝成功，支付宝返回的数据
  result.then((resp) => {
      res.send({
          data: {
              code: 200,
              success: true,
              msg: "支付中",
              paymentUrl: resp,
          },
      });
  });
})



// 引入axios
const axios = require("axios");

//支付交易查询
router.post('/api/paymentQuery', function (req, res, next) {
  //订单号
  let out_trade_no = req.body.out_trade_no;
  let trade_no = req.body.trade_no;
  // 支付宝配置
  const formData = new AlipayFormData();
  //调用setMethod 并传入get,会返回可以跳转到支付页面的url,
  formData.setMethod("get");
  // 支付时信息
  const bizContent = {
    out_trade_no,
    trade_no
  };
  formData.addField("bizContent", bizContent);

  // 返回promise
  const result = alipaySdk.exec(
    "alipay.trade.query",
    {},
    { formData: formData }
  ).catch(error => console.error('caught error!', error));
  //对接支付宝API
  result.then(resData => {
    axios({
      method: "GET",
      url: resData
    }).then(resdata => {
      let respondeCode = resdata.data.alipay_trade_query_response;
      if (respondeCode.code == 10000) {
        switch (respondeCode.trade_status) {
          case 'WAIT_BUYER_PAY':
            res.send({
              code: 10001,
              message: "支付宝有交易记录，没付款"
            })
            break;
          case 'TRADE_FINISHED':
            // 完成交易的逻辑
            res.send({
              code: 10002,
              message: "交易完成(交易结束，不可退款)"
            })
            break;
          case 'TRADE_SUCCESS':
           // 完成交易的逻辑
            res.send({
              code: 10002,
              message: "交易完成"
            })
            break;
          case 'TRADE_CLOSED':
            // 交易关闭的逻辑
            res.send({
              code: 10003,
              message: "交易关闭"
            })
            break;
        }
      } else if (respondeCode.code == 40004) {
        return res.send({
          code: 40004,
          message: "交易不存在"
        })
      }
    }).catch(err => {
      return res.send({
        code: 50000,
        msg: "交易失败",
        data: err
      })
    })
  })
})

  
module.exports = router;